const {
	Service
} = require("uni-cloud-router");
const {
	result_success,
	result_error
} = require('http-result-modle');
const {
	checkToken
} = require('common-uni-id');
const {
	mainSpaceId
} = require('config-main-space')
const db = uniCloud.database();
module.exports = class GatheringService extends(
	Service
) {

	async get(event) {
		let params;
		if (event.params) {
			params = event.params;
		} else if (event.data) {
			params = event.data;
		} else {
			return result_error('参数丢失', null);
		}
		if (!params) {
			return result_error('参数丢失', null);
		}
		if (!params._id) {
			return result_error('id不能为空', null);
		}
		let collectionShareData = await db.collection('wmzmall-collection-share').doc(params._id).get()
		collectionShareData = collectionShareData.data[0]
		if (collectionShareData.ispay) {
			return result_error('订单已支付');
		}
		let collectionData = await db.collection('wmzmall-collection').doc(collectionShareData.collectionId)
			.get()
		collectionData = collectionData.data[0]
		let validity = collectionData.validity
		let calDateTime = validity * 60 * 60 * 1000;
		let create_time = collectionShareData.create_time
		create_time = create_time + calDateTime
		let cDate = new Date()
		if (cDate && cDate.toString().indexOf('UTC') > -1) {
			cDate.setHours(cDate.getHours() + 8)
		}
		let cDateTime = cDate.getTime()
		if (cDateTime > create_time) {
			return result_error('支付链接已失效');
		}
		collectionData.money = (collectionData.money / 100).toFixed(2)
		collectionData.yj_money = (collectionData.yj_money / 100).toFixed(2)


		return result_success(collectionData);
	}
	async pay(event) {
		let data = event.data
		if (!data.collectionId) {
			return result_error('id不能为空');
		}
		/* if (!data.phone) {
			return result_error('手机号码不能为空');
		} */
		let userInfo
		if (this.ctx.event.uniIdToken) {
			const userRes = await checkToken(this.ctx.event.uniIdToken);
			if (userRes.userInfo) {
				userInfo = userRes.userInfo;
			}
		}
		if (!userInfo) {
			return result_error('登录失败,请杀掉进程重新登录');
		}
		let collectionShareData = await db.collection('wmzmall-collection-share').doc(data.collectionId).get()
		collectionShareData = collectionShareData.data[0]
		if (collectionShareData.ispay) {
			return result_error('订单已支付');
		}
		let collectionData = await db.collection('wmzmall-collection').doc(collectionShareData.collectionId)
			.get()
		collectionData = collectionData.data[0]
		if (!collectionData) {
			return result_error('数据错误');
		}
		let order_coupon_id = data.order_coupon_id
		let payMoney = data.payMoney * 100
		let yj_money = collectionData.yj_money
		let vip_price_discount = 0
		let memberRes
		if (collectionData.type === 0) {
			payMoney = collectionData.money
		}
		memberRes = await db.collection('wmzmall-member').doc(userInfo._id).get();
		memberRes = memberRes.data[0]
		payMoney = Math.ceil(payMoney) //parseInt(payMoney)
		let appId = userInfo.app_id
		let shopId = userInfo.shop_id
		let payWay = data.payWay
		let use_balance = data.use_balance
		let balance_money = 0
		if (use_balance) {
			if (!yj_money) {
				if (memberRes.vip_price_discount && payMoney >= 100) {
					vip_price_discount = (payMoney - payMoney * memberRes.vip_price_discount);
					payMoney = payMoney - vip_price_discount;
				}
				if (payMoney > memberRes.member_amount) {
					return result_error('余额不足');
				}
				await db.collection('wmzmall-collection').doc(collectionData._id).update({
					total: collectionData.total * 1 + payMoney * 1,
					count: collectionData.count * 1 + 1
				})
				await db.collection('wmzmall-collection-share').doc(collectionShareData._id)
					.update({
						ispay: true
					});

				let title = '收款';
				let cate = '远程收单订单';
				let type = 0;
				let auto_deliver
				let appletInfoData = await db.collection('wmz-applet-info').doc(appId).get()
				appletInfoData = appletInfoData.data[0]
				if (appletInfoData && appletInfoData.auto_deliver) {
					auto_deliver = appletInfoData.auto_deliver
				}
				let orderNo = '';
				let way = '余额';
				let yj_money = collectionData.yj_money
				let shopie = {
					app_id: appId,
					shop_id: shopId,
					order_no: orderNo,
					title: title,
					cate: cate,
					type: type,
					way: way,
					money: payMoney,
					yj_money: yj_money,
					creator_id: userInfo._id,
					creator_name: userInfo.username,
					create_time: new Date().getTime(),
					openid: userInfo.openid,
					auto_deliver: auto_deliver,
					share_user_id: collectionShareData.share_user_id,
					vip_price_discount: vip_price_discount
				};
				let addShopieResult = await db.collection('wmzmall-shopie').add(shopie);
				let tdb = uniCloud.database({
					provider: 'tencent',
					spaceId: mainSpaceId
				})
				await tdb.collection('wmzmall-shopie').add(shopie)

				await db.collection('wmzmall-member').doc(userInfo._id).update({
					member_amount: memberRes.member_amount - payMoney
				});
				const logRes = await db.collection('wmzmall-member-money-log').add({
					user_uid: userInfo._id,
					order_id: collectionShareData._id,
					money: payMoney,
					money_fmt: '-' + payMoney / 100,
					source: '订单支付',
					type: '支出',
					remark: `订单支付-${payMoney / 100}`,
					time: new Date().getTime(),
					is_delete: 0,
					create_uid: userInfo._id,
					create_time: new Date().getTime()
				});

				return result_success('支付成功');
			} else {
				balance_money = payMoney - yj_money
				if (memberRes.vip_price_discount && balance_money >= 100) {
					vip_price_discount = (balance_money - balance_money * memberRes.vip_price_discount);
					balance_money = balance_money - vip_price_discount
				}
				if (balance_money > memberRes.member_amount) {
					return result_error('余额不足');
				}
				payMoney = yj_money
			}
		} else {
			if(yj_money){
				if (memberRes.vip_price_discount && payMoney >= 100) {
					vip_price_discount = ((payMoney-yj_money) - (payMoney-yj_money) * memberRes.vip_price_discount);
					payMoney = payMoney - vip_price_discount;
				}
			}else{
				if (memberRes.vip_price_discount && payMoney >= 100) {
					vip_price_discount = (payMoney - payMoney * memberRes.vip_price_discount);
					payMoney = payMoney - vip_price_discount;
				}
			}
		}
		if(order_coupon_id){
			let coupon = await this.db.collection('wmzmall-marketing-coupon').doc(order_coupon_id)
				.get()
			coupon=coupon.data[0]
			if(coupon.price){
				payMoney = payMoney-coupon.price
			}	
		}
		
		const config = this.service.utils.getConfig();

		let orderNo = ('wmg_order_' + new Date().getTime() + (Math.round(Math.random() * 1000000) + '')
			.padStart(6, '0'));
		let payId = ('wmg_pay_' + new Date().getTime() + (Math.round(Math.random() * 1000000) + '')
			.padStart(6,
				'0'));
		let payTitle = collectionData.name;
		let openid = userInfo.openid;
		let notifyUrl = '/notify-collection';

		let gatheringOrder = {
			yj_money: yj_money,
			collectionShareId: data.collectionId,
			collectionId: collectionData._id,
			phone: data.phone,
			app_id: appId,
			shop_id: shopId,
			order_no: orderNo,
			order_pay_no: null,
			order_pay_way: payWay,
			order_pay_state: '待付款',
			order_pay_time: null,
			order_total_money: payMoney,
			order_surplus_money: payMoney,
			order_pay_money: payMoney,
			order_actually_pay: payMoney,
			order_actually_income: payMoney,
			order_third_discount: null,
			order_coupon: null,
			order_coupon_id: order_coupon_id,
			order_coupon_money: null,
			order_coupon_name: null,
			order_coupon_json: null,
			order_refund_money: null,
			order_refund_state: null,
			order_refund_reason: null,
			order_refund_desc: null,
			remark: null,
			state: '待付款',
			is_delete: 0,
			create_time: new Date().getTime(),
			create_uid: userInfo._id ? userInfo._id : null,
			create_uname: userInfo.username ? userInfo.username : null,
			delete_time: null,
			delete_uid: null,
			delete_uname: null,
			share_user_id: collectionShareData.share_user_id,
			balance_money: balance_money,
			vip_price_discount: vip_price_discount
		};

		let gatheringPay = {
			yj_money: yj_money,
			app_id: appId,
			shop_id: shopId,
			order_no: orderNo,
			pay_openid: openid,
			pay_money: payMoney,
			pay_title: payTitle,
			pay_way: payWay,
			pay_original: null,
			pay_trade_type: 'JSAPI',
			pay_id: payId,
			pay_pre_id: null,
			pay_res: null,
			pay_time: null,
			pay_notify: null,
			pay_state: '待付款',
			version: 1,
			is_delete: 0,
			create_time: new Date().getTime(),
			create_uid: userInfo._id ? userInfo._id : null,
			create_uname: userInfo.username ? userInfo.username : null,
			share_user_id: collectionShareData.share_user_id,
			balance_money: balance_money
		};

		let payOrderInfo;
		switch (payWay) {
			case '支付宝':

				let alipayOrderInfo = await this.service.alipay.pay(userInfo.app_id, openid, orderNo,
					payMoney,
					payTitle, notifyUrl + '/alipay');
				gatheringPay.pay_res = JSON.stringify(alipayOrderInfo);

				uniCloud.logger.info("alipayOrderInfo: ", gatheringPay.pay_res);

				if (!alipayOrderInfo.data) {
					return result_error(alipayOrderInfo.data || '获取支付宝支付订单号失败', null);
				}

				gatheringPay.pay_original = '支付宝支付';
				gatheringPay.pay_pre_id = alipayOrderInfo.prepayId;
				payOrderInfo = {
					trade_no: alipayOrderInfo.data
				};

				break;
			case '微信支付':

				let wechatOrderInfo = await this.service.wechat.pay(appId, openid, orderNo, payMoney,
					payTitle,
					notifyUrl + '/wechat');
				console.log(wechatOrderInfo)
				gatheringPay.pay_res = JSON.stringify(wechatOrderInfo);

				if (!wechatOrderInfo.data.package) {
					return result_error(payMoney + ":" + wechatOrderInfo.data);
				}

				gatheringPay.pay_original = '微信支付';
				gatheringPay.pay_pre_id = wechatOrderInfo.data.package;
				payOrderInfo = wechatOrderInfo.data;
				break;
			default:
				return result_error('支付方式参数不正确', null);
		}
		payOrderInfo.pay_id = payId;

		const transaction = await db.startTransaction();
		try {
			let addOrderResult = await transaction.collection('wmzmall-collection-order').add(
				gatheringOrder);
			if (!addOrderResult || !addOrderResult.id) {
				return result_error('新增远程收单订单数据失败', null);
			}
			let addPayResult = await transaction.collection('wmzmall-collection-pay').add(gatheringPay);
			if (!addPayResult || !addPayResult.id) {
				return result_error('新增远程收单支付数据失败', null);
			}
			await transaction.commit();

		} catch (e) {
			await transaction.rollback();
			console.error(`transaction error`, e);
		} finally {
			console.log("payOrderInfo")
			console.log(payOrderInfo)
			return result_success(payOrderInfo, '收款码下单支付成功');
		}
	}
};